package com.ppgames.gm.gmsystem.interceptor;

import com.ppgames.gm.gmsystem.GmContext;
import com.ppgames.gm.gmsystem.GmCore;
import com.ppgames.gm.gmsystem.auth.OptInfo;
import com.ppgames.gm.gmsystem.util.JsonHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class GCoreHandlerInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(GCoreHandlerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
/*        logger.info("添加跨域访问头配置，Access-Control-Allow-Origin:*");
        //跨域访问CORS
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE,HEAD");
        response.addHeader("Access-Control-Allow-Headers", "S_ID,content-type");
        response.addHeader("Access-Control-Max-Age", "3600000");
        response.addHeader("Access-Control-Allow-Credentials", "true");

        //让请求，不被缓存，
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);*/

        String token = request.getParameter(GmCore.Constant.TOKEN_VIEW_FLAG);
        if (token == null || token.isEmpty()) {
            return false;
        } else {
            OptInfo optInfo = JsonHelper.toObject(GmCore.TOKEN_CACHE.get(GmCore.Constant.TOKEN_INFO_FLAG + token), OptInfo.class);
            String cacheToken = optInfo.getToken();
            if (!cacheToken.equals(token)) {
                return false;
            }
        }


        GmContext context = new GmContext();
        /**
         * 通过拦截器 把mesage记录到这次请求中的context中。
         * 每一次请求对应一个Context
         * token ：做api授权的时候用到
         */
        context.setId(GmCore.Util.createUUID());
        context.setSourceIP(GmCore.Util.getRealIP(request));
        context.setRequestUri(request.getRequestURI());
        context.setToken(token);
        GmContext.setContext(context);
        logger.trace("[{}] {}{} from {}", request.getMethod(), request.getRequestURI(), request.getQueryString() == null ? "" : "?" + request.getQueryString(), context.getSourceIP());
        logger.debug("==================================preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
        logger.debug("==================================postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        logger.debug("==================================afterCompletion");
    }


}
